<template>
  <div style="width: 100vw; overflow-x: hidden">
    <div class="cropper-content">
      <div class="cropper-box">
        <div class="cropper">
          <vue-cropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.outputSize"
            :outputType="option.outputType"
            :info="option.info"
            :canScale="option.canScale"
            :autoCrop="option.autoCrop"
            :autoCropWidth="option.autoCropWidth"
            :autoCropHeight="option.autoCropHeight"
            :fixed="option.fixed"
            :fixedNumber="option.fixedNumber"
            :full="option.full"
            :fixedBox="option.fixedBox"
            :canMove="option.canMove"
            :canMoveBox="option.canMoveBox"
            :original="option.original"
            :centerBox="option.centerBox"
            :height="option.height"
            :infoTrue="option.infoTrue"
            :maxImgSize="option.maxImgSize"
            :enlarge="option.enlarge"
            :mode="option.mode"
            @realTime="realTime"
            @imgLoad="imgLoad" :key="keyIndex">
          </vue-cropper>
        </div>
      </div>
      <!--预览效果图-->
      <div class="show-preview">
        <div :style="previews.div" class="preview">
          <Image :src="previews.url" :style="previews.img"></Image>
        </div>
      </div>
    </div>
    <!--底部操作工具按钮-->
    <div class="footer-btn">
      <Space direction="vertical">
        <div>
          名称：<span style="flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
                     :title="fileInfo.name">
              {{ fileInfo.name || '- -' }}
            </span>
          &nbsp;&nbsp;
          大小：{{ ((fileInfo.size / 1024 / 1024) || 0).toFixed(2) }} M
          &nbsp;&nbsp;
          类型：
          <Tag size="small">{{ fileInfo.type || '未知' }}</Tag>
        </div>
        <Space wrap>
          <leading-in-file label="选择图片" @change="selectImg($event)"></leading-in-file>
          <Button type="success" plain icon="md-expand" @click="changeScale(1)">放大</Button>
          <Button type="success" plain icon="md-contract" @click="changeScale(-1)">缩小</Button>
          <Button type="success" plain icon="el-icon-refresh-left" @click="rotateLeft">
            <Icon type="md-refresh" style="transform: rotateY(180deg)"/>
            左旋转
          </Button>
          <Button type="success" plain icon="md-refresh" @click="rotateRight">右旋转</Button>
        </Space>
        <!--        <Button type="error" plain icon="el-icon-refresh-right" @click="clear">清除</Button>-->
        <Space :size="14" wrap>
          <div>
            锁定宽高比
            <Switch
              v-model="option.fixed"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="fixedSwitchChange">
            </Switch>
          </div>
          <div>
            宽
            <InputNumber @on-change="widthInput" v-model="cropWidth"></InputNumber>
          </div>
          <div>
            高
            <InputNumber @on-change="heightInput" v-model="cropHeight"></InputNumber>
          </div>
          <div>
            图片质量
            <InputNumber :step="0.1" :min="0" :max="1" v-model="option.outputSize"></InputNumber>
          </div>
          <Button type="primary" @click="exportImg">导出</Button>
        </Space>
      </Space>
    </div>
  </div>
</template>

<script>
import {VueCropper} from 'vue-cropper';
import 'vue-cropper/dist/index.css';
import LeadingInFile from "@/components/LeadingInFile";
import {FileUtil} from "baitu";

export default {
  name: "CropperImage",
  components: {
    LeadingInFile,
    VueCropper
  },
  props: ['Name'],
  data() {
    return {
      keyIndex: 0,
      imageTypes: ["jpg", "jpeg", "png"],
      fileType: "",
      dialogVisible: false,
      cropWidth: 0,
      cropHeight: 0,
      fixedNumberTemp: [200, 200],
      fileInfo: {},
      name: this.Name,
      previews: {},
      option: {
        img: '',             //裁剪图片的地址
        outputSize: 1,       //裁剪生成图片的质量(可选0.1 - 1)
        outputType: 'png',  //裁剪生成图片的格式（jpeg || png || webp）
        info: true,          //图片大小信息
        canScale: true,      //图片是否允许滚轮缩放
        autoCrop: true,      //是否默认生成截图框
        autoCropWidth: 200,  //默认生成截图框宽度
        autoCropHeight: 200, //默认生成截图框高度
        fixed: true,         //是否开启截图框宽高固定比例
        fixedNumber: [200, 200], //截图框的宽高比例
        full: false,         //false按原比例裁切图片，不失真
        fixedBox: false,      //固定截图框大小，不允许改变
        canMove: true,      //上传图片是否可以移动
        canMoveBox: true,    //截图框能否拖动
        original: false,     //上传图片按照原始比例渲染
        centerBox: false,    //截图框是否被限制在图片里面
        height: true,        //是否按照设备的dpr 输出等比例图片
        infoTrue: false,     //true为展示真实输出图片宽高，false展示看到的截图框宽高
        maxImgSize: 3000,    //限制图片最大宽度和高度
        enlarge: 1,          //图片根据截图框输出比例倍数
        mode: '230px 150px'  //图片默认渲染方式
      }
    };
  },
  watch: {
    cropWidth: {
      handler(n, o) {
        if (n !== o) {
          this.fixedNumberTemp = [this.cropWidth, this.cropHeight]
        }
      }
    },
    cropHeight: {
      handler(n, o) {
        if (n !== o) {
          this.fixedNumberTemp = [this.cropWidth, this.cropHeight]
        }
      }
    }
  },
  methods: {
    //初始化函数
    imgLoad(msg) {
      console.log("工具初始化函数=====" + msg)
    },
    //图片缩放
    changeScale(num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    //向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    //向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    //实时预览函数
    realTime(data) {
      this.previews = data
      this.previews.div = {
        width: data.w + "px",
        height: data.h + "px",
        overflow: "hidden",
        margin: "0",
        zoom: 100 / data.w
      }
      this.cropHeight = data.h;
      this.cropWidth = data.w;
    },
    //选择图片
    selectImg(e) {
      let file = e.target.files[0]
      this.fileInfo = file;
      if (!/.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
        this.$message({
          message: '图片类型要求：jpeg、jpg、png',
          type: "error"
        });
        return false
      }
      //转化为blob
      let reader = new FileReader()
      reader.onload = (e) => {
        let data
        if (typeof e.target.result === 'object') {
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        this.option.img = data
      }
      //转化为base64
      reader.readAsDataURL(file)
    },
    //保存图片
    exportImg() {
      this.$refs.cropper.getCropBlob((data) => {
        FileUtil.downloadBlob(data, 'simple-tool-cropper-image' + Date.now() + '.png');
      });
    },
    widthInput(w) {
      this.option.autoCropWidth = w;
    },
    heightInput(h) {
      this.option.autoCropHeight = h;
    },
    fixedSwitchChange(v) {
      if (v) {
        this.option.fixedNumber = this.fixedNumberTemp;
      }
    },
    clear() {
      this.$refs.cropper.stopCrop()
    }
  },
  mounted() {
    window.onresize = () => {
      this.keyIndex = this.keyIndex + 1
    }
  },
  destroyed() {
    window.onresize = null;
  },
}
</script>

<style scoped lang="scss">
.mobile {
  .cropper-content {
    .cropper {
      height: 80vh !important;
    }
  }
}

.cropper-content {
  position: relative;
  .cropper-box {
    width: 100%;

    .cropper {
      width: 100vw;
      height: calc(100vh - 187px);
    }
  }

  .show-preview {
    position: absolute;
    right: 0;
    bottom: 0;

    .preview {
      overflow: hidden;
      border: 1px solid #67c23a;
      background: #cccccc;
    }
  }
}

.footer-btn {
  padding: 20px 0 30px 20px;
}
</style>
